package fei.typhoon.engine.logic;


public abstract class FeiLogic extends Thread {

	private final static byte STATE_RUNNING = 1;
	private final static byte STATE_PAUSE = 2;
	private final static byte STATE_STOP = 0;

	private byte state = STATE_STOP;
	private FeiLogic lock = null;
	private long refreshTime = 3;

	public abstract void logicRun();

	public FeiLogic() {
		lock = this;
	}

	@Override
	public final void run() {
		while (state != STATE_STOP) {
			synchronized (lock) {
				logicRun();
				try {
					if (state == STATE_PAUSE) {
						lock.wait();
					} else {
						lock.wait(refreshTime);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
					break;
				}
			}
		}
	}

	@Override
	public synchronized void start() {
		state = STATE_RUNNING;
		super.start();
	}

	public void start(long refreshTime) {
		this.refreshTime = refreshTime;
		start();
	}

	public synchronized void pauseLogic() {
		state = STATE_PAUSE;
	}

	public synchronized void resumeLogic() {
		state = STATE_RUNNING;
		synchronized (lock) {
			lock.notify();
		}
	}

	public synchronized void stopLogic() {
		state = STATE_STOP;
		interrupt();
	}

	public long getRefreshTime() {
		return refreshTime;
	}

	public void setRefreshTime(long refreshTime) {
		this.refreshTime = refreshTime;
	}
}
